﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Sql;
using System.Web;
using System.Web.Mvc;
using TjZheng.CMS.Process;
using TjZheng.Controls;
using TjZheng.Framework;
using CJAtech.BBS.Business;
using CJAtech.BBS.DataEntity;
using TjZheng.Base;
using TjZheng.CMS.Areas.BBS.Models;
using System.Text;
using System.Data;
using System.Data.Common;
using Aspose.Cells;
using TjZheng.CMS.Filters;
using TjZheng.Domain.DataEntity;

namespace TjZheng.CMS.Areas.BBS.Controllers
{
    [DbSetFilter]
    public class VoteInfoController : CMSController
    {
        //
        // GET: /BBS/VoteInfo/

        BizVoteHead voteHeadDao { get; set; }
        BizVoteDetail voteDetailDao { get; set; }
        BizCustomerVote customerVoteDao { get; set; }
        public VoteInfoController()
        {
            //voteHeadDao = new BizVoteHead(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            //voteDetailDao = new BizVoteDetail(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
        }
        DbSetInfo objDbSetInfo
        {
            get
            {
                return ViewBag.DbSetInfo as DbSetInfo;
            }
        }
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
  
        /// <summary>
        /// 列表数据或搜索数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页条数</param>
        /// <returns></returns>
        [QueryMsSqlFilter("ArticleID")]
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult ListJson(int page, int rows,int ArticleID)
        {
            voteHeadDao = new BizVoteHead(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            //string sql = string.Empty;
            //if (ArticleID != 0)
            //{
            //    sql = " and ArticleID=" + ArticleID;
            //}
            //StringBuilder strBuilder = new StringBuilder();
            //strBuilder.Append("  SELECT TOP " + rows + " *  FROM ( SELECT ROW_NUMBER() OVER (ORDER BY UpdateTime desc) AS RowNumber,* FROM BBS_VoteHead_TB where IsDel=0  " + sql + "  ) A WHERE RowNumber >" + rows * (page - 1));
            //var data = voteHeadDao.ExecuteQuerySql(strBuilder.ToString(), null);
            //return Json(data);
            return Json(voteHeadDao.GetPageResult(page - 1, rows,"IsDel=0 and ArticleID="+ArticleID , QueryResult.Parameters, "UpdateTime desc"));
        }


        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="VoteHeadID"></param>
        /// <returns></returns>
        public ActionResult EditPage(Guid? VoteHeadID)
        {
            CJ_VoteInfo head = new Models.CJ_VoteInfo();
            head.DetailList = new List<Models.CJ_VoteDetail>();
            if(VoteHeadID!=null&&VoteHeadID!=Guid.Empty)
            {
                voteHeadDao = new BizVoteHead(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
                var voteHead = voteHeadDao.GetRecord(new Guid(VoteHeadID.ToString()));
                StringBuilder strBuilder = new StringBuilder();
                //strBuilder.Append("     select a.VoteDetailID ,VoteHeadID,ArticleID ,TextContent ,ResourceContent,IsDel ,CreateTime,UpdateTime,Num=case when b.Num is null then 0 else b.Num end  from (select * from BBS_VoteDetail_TB where IsDel=0) a left join ( select Num=count(1),VoteDetailID from BBS_CustomerVote_TB  group by VoteDetailID ) b on a.VoteDetailID=b.VoteDetailID  where VoteHeadID=@VoteHeadID");
                //DataTable dt = voteHeadDao.ExecuteQuerySql(strBuilder.ToString(), "VoteHeadID".CreateParameters(DataBaseType.MsSql, VoteHeadID));
                strBuilder.Append("     select a.VoteDetailID ,VoteHeadID,ArticleID ,TextContent ,ResourceContent,IsDel ,CreateTime,UpdateTime,Num=case when b.Num is null then 0 else b.Num end  from (select * from BBS_VoteDetail_TB where IsDel=0) a left join ( select Num=count(1),VoteDetailID from BBS_CustomerVote_TB  group by VoteDetailID ) b on a.VoteDetailID=b.VoteDetailID  where VoteHeadID='" + VoteHeadID + "'");
                DataTable dt = voteHeadDao.ExecuteQuerySql(strBuilder.ToString(), null);
                //CJ_VoteInfo head = new Models.CJ_VoteInfo();
                head.VoteHeadID = voteHead.VoteHeadID;
                head.VoteTitle = voteHead.VoteTitle;
                head.MaxCheckNum = voteHead.MaxCheckNum;
                head.ArticleID = voteHead.ArticleID;
                head.ContentType = voteHead.ContentType;
              
                int totalCount = Convert.ToInt32(dt.Compute("sum(Num)", ""));
                int totalCount2 = Convert.ToInt32(dt.Compute("sum(ArticleID)", ""));
                decimal percentage = 0m;
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    CJ_VoteDetail d = new Models.CJ_VoteDetail();
                    d.VoteDetailID = new Guid(row["VoteDetailID"].ToString());
                    d.VoteHeadID = new Guid(row["VoteHeadID"].ToString());
                    d.TextContent = row["TextContent"].ToString();
                    d.ResourceContentList = row["ResourceContent"].ToString().Split(',').ToList();
                    d.VoteNum = Convert.ToInt32(row["Num"].ToString());
                    if (totalCount != 0)
                    {
                        if (i == dt.Rows.Count - 1)
                        {
                            d.VotePercentage = 100 - percentage;
                        }
                        else
                        {
                            d.VotePercentage = Convert.ToDecimal(d.VoteNum * 100) / totalCount;
                            d.VotePercentage = Convert.ToDecimal(d.VotePercentage.ToString("f2"));
                            percentage += d.VotePercentage;
                        }
                    }
                    head.DetailList.Add(d);
                }
            }
            return View(head);
        }

        /// <summary>
        /// 编辑页面-保存
        /// </summary>
        /// <param name="VoteInfo"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult Save(CJ_VoteInfo VoteInfo)
        {
            var r = Request;
            //Request.Files.GetMultiple("file")
            voteHeadDao = new BizVoteHead(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            voteDetailDao = new BizVoteDetail(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            InvokeResult objInvokeResult = new InvokeResult();
            objInvokeResult.ResultCode = "ProvideNull";
            objInvokeResult.ResultMessage = "保存失败";
            #region valid
            if (VoteInfo == null)
            {
                objInvokeResult.ResultMessage = "保存对象实体不能为空";
                return Json(objInvokeResult, "text/plain");
            }
            if (String.IsNullOrEmpty(VoteInfo.VoteTitle))
            {
                objInvokeResult.ResultMessage = "投票标题不能为空！";
                return Json(objInvokeResult, "text/plain");
            }
            if (VoteInfo.ArticleID == 0)
            {
                objInvokeResult.ResultMessage = "投票文章ID丢失！";
                return Json(objInvokeResult, "text/plain");
            }
            if (VoteInfo.MaxCheckNum == 0)
            {
                objInvokeResult.ResultMessage = "投票最大勾选数量不能为空！";
                return Json(objInvokeResult, "text/plain");
            }
            if (VoteInfo.DetailList == null || VoteInfo.DetailList.Count == 0)
            {
                objInvokeResult.ResultMessage = "投票选项信息不能为空！";
                return Json(objInvokeResult, "text/plain");
            }
            if (VoteInfo.MaxCheckNum > VoteInfo.DetailList.Count)
            {
                objInvokeResult.ResultMessage = "投票数不能超过投票选项数量！";
                return Json(objInvokeResult, "text/plain");
            }
            foreach (var detail in VoteInfo.DetailList)
            {
                //if (string.IsNullOrEmpty(detail.TextContent) && detail.ResourceContentList == null && detail.ResourceContentList.Count == 0)
                //{
                //    objInvokeResult.ResultMessage = "投票选项内容不能全部为空！";
                //    return Json(objInvokeResult, "text/plain");
                //}
                if (VoteInfo.ContentType !=1&&VoteInfo.ContentType !=2)
                {
                    if (String.IsNullOrEmpty(detail.TextContent))
                    {
                        objInvokeResult.ResultMessage = "投票选项文本内容不能为空！";
                        return Json(objInvokeResult, "text/plain");
                    }
                }
                if (VoteInfo.ContentType != 0)
                {
                    if (detail.ResourceContentList == null || detail.ResourceContentList.Count == 0)
                    {
                        objInvokeResult.ResultMessage = "投票选项资源内容不能为空！";
                        return Json(objInvokeResult, "text/plain");
                    }
                    foreach (var res in detail.ResourceContentList)
                    {
                        if (string.IsNullOrEmpty(res))
                        {
                            objInvokeResult.ResultMessage = "请上传资源！";
                            return Json(objInvokeResult, "text/plain");
                        }
                    }
                }
            }
            #endregion
            #region 上传文件赋值
            List<string> responseUrls = "PictureUrl".SaveFilesAsList();
            int num = 0;
           
            for (var i = 0; i < VoteInfo.DetailList.Count; i++)
            {
                if (VoteInfo.DetailList[i].ResourceContentList != null && VoteInfo.DetailList[i].ResourceContentList.Count != 0)
                {
                    for (var j = 0; j < VoteInfo.DetailList[i].ResourceContentList.Count; j++)
                    {
                        if (VoteInfo.DetailList[i].ResourceContentList[j].Split('.').Length == 2)
                        {
                            VoteInfo.DetailList[i].ResourceContentList[j] = responseUrls[num];
                            num++;
                        }
                    }
                }
            }
            #endregion
            int ContentType = Convert.ToInt32(VoteInfo.ContentType);
            if (VoteInfo.VoteHeadID == Guid.Empty)
            {
                VoteHead head = new VoteHead();
                head.ArticleID = VoteInfo.ArticleID;
                head.ContentType = VoteInfo.ContentType;
                head.CreateTime = DateTime.Now;
                head.IsDel = false;
                head.MaxCheckNum = VoteInfo.MaxCheckNum;
                head.UpdateTime = DateTime.Now;
                head.VoteTitle = VoteInfo.VoteTitle;
                //head.VoteHeadID = Guid.NewGuid();
                voteHeadDao.Add(head);
                foreach (var detail in VoteInfo.DetailList)
                {
                    VoteDetail d = new VoteDetail();
                    //d.VoteDetailID = Guid.NewGuid();
                    d.ArticleID = head.ArticleID;
                    d.CreateTime = DateTime.Now;
                    d.IsDel = false;
                    if (ContentType != 0)
                    {
                        d.ResourceContent = String.Join(",", detail.ResourceContentList).ToString().Trim(',');
                    }
                    if (ContentType != 1 && ContentType != 2)
                    {
                        d.TextContent = detail.TextContent;
                    }
                    d.UpdateTime = DateTime.Now;
                    d.VoteHeadID = head.VoteHeadID;
                    voteDetailDao.Add(d);
                }
            }
            else
            {
                VoteHead head = voteHeadDao.GetRecord(VoteInfo.VoteHeadID);
                if (head == null)
                {
                    objInvokeResult.ResultMessage = "该编辑对象不存在";
                    return Json(objInvokeResult, "text/plain");
                }
                head.ContentType = VoteInfo.ContentType;
                head.MaxCheckNum = VoteInfo.MaxCheckNum;
                head.UpdateTime = DateTime.Now;
                head.VoteTitle = VoteInfo.VoteTitle;
                voteHeadDao.Update(head);
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append("   select VoteDetailID from BBS_VoteDetail_TB where IsDel=0 and VoteHeadID='"+VoteInfo.VoteHeadID +"'");
                DataTable dt = voteHeadDao.ExecuteQuerySql(strBuilder.ToString(), null);
                List<Guid> ids = new List<Guid>();
                foreach ( DataRow dr in dt.Rows)
                {
                    ids.Add( new Guid(dr["VoteDetailID"].ToString()));
                }
                //区分新增，修改，删除
                List<Guid> detailIDs = VoteInfo.DetailList.Where(x => x.VoteDetailID != Guid.Empty).Select(x => x.VoteDetailID).ToList();
                //删除
                List<Guid> dids = ids.Where(x => !detailIDs.Contains(x)).ToList();
                foreach (var did in dids)
                {
                    VoteDetail d = voteDetailDao.GetRecord(did);
                    d.IsDel = true;
                    voteDetailDao.Update(d);
                }
                //添加
                List<CJ_VoteDetail> aList = VoteInfo.DetailList.Where(x => x.VoteDetailID == Guid.Empty).ToList();
                foreach (var a in aList)
                {
                    VoteDetail d = new VoteDetail();
                    d.VoteHeadID = VoteInfo.VoteHeadID;
                    d.UpdateTime = DateTime.Now;
                    d.CreateTime = DateTime.Now;
                    d.IsDel = false;
                    d.ArticleID = VoteInfo.ArticleID;
                    if (ContentType != 0)
                    {
                        d.ResourceContent = String.Join(",", a.ResourceContentList).ToString().Trim(',');
                    }
                    if (ContentType != 1 && ContentType != 2)
                    {
                        d.TextContent = a.TextContent;
                    }
                    voteDetailDao.Add(d);
                }
                //修改
                List<Guid> mids = ids.Where(x => detailIDs.Contains(x)).ToList();
                foreach (var mid in mids)
                {
                    VoteDetail d = voteDetailDao.GetRecord(mid);
                    CJ_VoteDetail cd = VoteInfo.DetailList.Where(x => x.VoteDetailID == mid).FirstOrDefault();
                    d.UpdateTime = DateTime.Now;
                    if (ContentType != 0)
                    {
                        d.ResourceContent = String.Join(",", cd.ResourceContentList).ToString().Trim(',');
                    }
                    else
                    {
                        d.ResourceContent = "";
                    }
                    if (ContentType != 1 && ContentType != 2)
                    {
                        d.TextContent = cd.TextContent;
                    }
                    else
                    {
                        d.TextContent = "";
                    }
                    voteDetailDao.Update(d);
                }
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "保存成功";
            return Json(objInvokeResult, "text/plain");
        }

        public ActionResult Delete(Guid? id)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (id == null || id == Guid.Empty)
            {
                objInvokeResult.ResultCode = "IDNull";
                objInvokeResult.ResultMessage = "请先选择一条数据";
                return Json(objInvokeResult, "text/plain");
            }
            voteHeadDao = new BizVoteHead(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            voteDetailDao = new BizVoteDetail(objDbSetInfo.ConnectionString, objDbSetInfo.TableExtension);
            VoteHead head = voteHeadDao.GetRecord(new Guid(id.ToString ()));
            if (head == null)
            {
                objInvokeResult.ResultCode = "Success";
                objInvokeResult.ResultMessage = "删除成功";
                return Json(objInvokeResult, "text/plain");
            }
            head.IsDel = true;
            voteHeadDao.Update(head);
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("  select VoteDetailID from BBS_VoteDetail_TB where IsDel=0 and VoteHeadID='" + id.ToString() + "'");
            var dt = voteDetailDao.ExecuteQuerySql(strBuilder.ToString(), null);
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                Guid detailID = new Guid(dr["VoteDetailID"].ToString());
                VoteDetail vd = voteDetailDao.GetRecord(detailID);
                vd.IsDel = true;
                voteDetailDao.Update(vd);
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "删除成功";
            return Json(objInvokeResult, "text/plain");
        }
    }
}
